<!doctype html>
<html>

<head>
  <title>GeoChallenge</title>
  <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
  <script src="../components/platform/platform.js"></script>
  <link rel="import" href="../components/font-roboto/roboto.html">
  <link rel="import" href="../components/core-header-panel/core-header-panel.html">
  <link rel="import" href="../components/core-scaffold/core-scaffold.html">
  <link rel="import" href="../components/paper-toast/paper-toast.html">
  <link rel="import" href="challenge-list.html">
  <link rel="import" href="challenge-map.html">
  <style>
  html,body {
    height: 100%;
    margin: 0;
    background-color: #E5E5E5;
    font-family: 'RobotoDraft', sans-serif;
  }
  </style>

  <script>
    // This function adapted from http://www.html5rocks.com/en/tutorials/geolocation/trip_meter/#toc-step6
    // Calculates distance in meters.
    function calculateDistance(lat1, lon1, lat2, lon2) {
      var R = 6371; // km
      var dLat = (lat2 - lat1).toRad();
      var dLon = (lon2 - lon1).toRad();
      var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
              Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
              Math.sin(dLon / 2) * Math.sin(dLon / 2);
      var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
      var d = R * c;
      return d * 1000;
    }
    Number.prototype.toRad = function() {
      return this * Math.PI / 180;
    }
  </script>

  <polymer-element name="geo-main">
    <template>
      <core-ajax
          auto
          url="http://bright-petal-676.appspot.com/challenge"
          method="GET"
          handleAs="json"
          params='{"id": "{{ challenge_id }}" }'
          response='{{ challenge }}'>
      </core-ajax>

      <paper-toast id="challenge_toast"></paper-toast>

      <core-scaffold>
        <core-header-panel navigation flex mode="seamed">
          <core-toolbar>Application</core-toolbar>
          <challenge-list challenge_id="{{challenge_id}}" new_challenge="{{ new_challenge }}"></challenge-list>
        </core-header-panel>
        <div tool>Title</div>
        <challenge-map challenge="{{ challenge }}" user_position="{{ user_position }}" current_checkpoint_index="{{ current_checkpoint_index }}" fit></challenge-map>
      </core-scaffold>
    </template>
    <script>
      Polymer('geo-main', {
        challenge_id: "",
        current_checkpoint_index: 0,
        challenge_idChanged: function(old_id, new_id) {
          console.log("new_id: " + new_id);
        },
        new_challengeChanged: function(old_val, new_val) {
          console.log("new challenge: " + new_val);
          window.location.href = "record_challenge.html";
        },
        user_positionChanged: function(old_pos, new_pos) {
          if (this.challenge && this.current_checkpoint_index < this.challenge.checkpoints.length) {
            console.log("remaining checkpoints: " + this.challenge.checkpoints.length - this.current_checkpoint_index);
            var checkpoint = this.challenge.checkpoints[this.current_checkpoint_index];
            var distance = calculateDistance(new_pos.coords.latitude, new_pos.coords.longitude, checkpoint.latitude, checkpoint.longitude);

            if (distance <= checkpoint.accuracy + Math.min(20.0, new_pos.coords.accuracy)) {
              this.current_checkpoint_index++;
              if (this.current_checkpoint_index >= this.challenge.checkpoints.length) {
                this.$.challenge_toast.text = "Challenge completed!";
              } else {
                this.$.challenge_toast.text = "Checkpoint achieved " + distance + " meters away!";
              }
              this.$.challenge_toast.show();
            }
          }
        }
      });
    </script>
  </polymer-element>
</head>

<body unresolved touch-action="auto">
  <geo-main></geo-main>
</body>

</html>
